<template>
  <div class="app-container">
    <Find @clickNumber="clickNumber" :searchImg="false" :formList="formList1" @findClicked="findData" @Launchform="Launchform3" />
    <el-card style="margin-top: 10px" shadow="always" :body-style="{ padding: '20px' }">
      <h1>用户管理</h1>
      <Tables
        :functionList1="false"
        :functionList="true"
        @modifTable1="modifTable1"
        :updated="true"
        :deleteButton="true"
        @deleteRow="deleteRow"
        @currentRow="currentRowListOeder"
        :isLoading="isLoading7"
        :tableHeader="tableHeader"
        :tableData="usersQueryTableDate"
        :TableHeight="73"
      />
      <PageModule :PageData="{ total }" @pageSizeChange="handleSizeChangeTk" @pageChange="handleCurrentChangeTk" />
      <el-button style="margin-top: 30px" type="primary" size="default" @click="resetPasswordMethods">重置密码</el-button>

      <PageModule :PageData="{ pageSizeShow: true }" />
    </el-card>

    <el-dialog v-model="dialogVisible1" width="80%" class="dialog pb0">
      <Find :OriginalFilter="{ static: true }" :searchImg="false" :formList="formList2" @Launchform="Launchform" @findClicked="findData1" />
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'UserManagement'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import {
  usersQuery,
  postQuery,
  DispatchDepartment,
  addUsers,
  deleteUser,
  resetPassword,
  midifne
} from '@/api/SystemManagementModule/SystemFileManagement/UserManagement'
import { DepartmentAllInquiry } from '@/api/WarehouseDepartment/FactoryStorage/ReplenishmentInvoicing'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, onMounted } from 'vue'

// 修改
const modifTable1 = async (row: any) => {
  if (row.deptName !== undefined) {
    if (row.deptName.selectValue.split(' ').length > 1) {
      row.deptNo = row.deptName.selectValue.split(' ')[0]

      delete row.deptName
    } else {
      delete row.posName
      delete row.deptNo
    }
  }

  if (row.lockStatus !== undefined) {
    row.lockStatus = row.lockStatus.selectValue === '正常使用' ? 'N' : 'Y'
  }

  if (row.drawDept?.selectValue !== undefined) {
    row.drawDept = row.drawDept.selectValue.split(' ')[1]
  }

  if (row.dispatchDept !== undefined) {
    row.dispatchDept = row.dispatchDept.selectValue
  }

  if (row.netFlag !== undefined) {
    row.netFlag = row.netFlag.selectValue === '内网' ? 'N' : 'Y'
  }

  if (row.posName !== undefined) {
    if (row.posName.selectValue.split(' ').length > 1) {
      row.posId = row.posName.selectValue.split(' ')[0]
      delete row.posName
    } else {
      delete row.posName
      delete row.posId
    }
  }

  try {
    const result = await midifne(row)
    if (result.code === 200) {
      JMessage.success(result.message)
      usersQueryMethods()
    } else {
      JMessage.error(result.message)
    }
  } catch (error) {
    JMessage.error('修改失败')
  }
}

// 修改
const deleteRow = (row: any) => {
  deleteUserMethodsParms.value.userId = row.userId
  handleCloseMateriaLKlc5()
}

// 重置密码
const resetPasswordMethods = async () => {
  if (deleteUserMethodsParms.value.userId === '') {
    JMessage.warning('请选择需要重置密码的数据')
  } else {
    try {
      const result = await resetPassword(deleteUserMethodsParms.value.userId)
      if (result.code === 200) {
        usersQueryMethods()
        deleteUserMethodsParms.value.userId = ''
        JMessage.success(result.message)
      } else {
        JMessage.error(result.message)
      }
    } catch (error) {
      JMessage.error('重置密码失败')
    }
  }
}

// 删除用户
const deleteUserMethodsParms = ref({
  userId: ''
})

const currentRowListOeder = (row: any) => {
  deleteUserMethodsParms.value.userId = row.userId
}

const deleteUserMethods = async () => {
  try {
    const result = await deleteUser(deleteUserMethodsParms.value.userId)
    if (result.code === 200) {
      usersQueryMethods()
      deleteUserMethodsParms.value.userId = ''
      JMessage.success(result.message)
    } else {
      JMessage.error(result.message)
    }
  } catch (error) {
    JMessage.error('删除失败')
  }
}

// 添加用户
const addUsersParms = ref({
  chiName: '',
  deptNo: '',
  engName: '',
  posId: '',
  remark: ''
})

const addUsersMethods = async () => {
  if (
    addUsersParms.value.chiName === '' ||
    addUsersParms.value.deptNo === '' ||
    addUsersParms.value.engName === '' ||
    addUsersParms.value.posId === '' ||
    addUsersParms.value.remark === ''
  ) {
    JMessage.warning('数据不完善')
  } else {
    try {
      const result = await addUsers(addUsersParms.value)
      if (result.code === 200) {
        dialogVisible1.value = false
        usersQueryMethods()
        clearFormList6()
        JMessage.success(result.message)
      } else {
        JMessage.error(result.message)
      }
    } catch (error) {
      JMessage.error('添加用户失败')
    }
  }
}

const clearFormList6 = () => {
  formList2.value.forEach((item) => {
    if (item.type === 'input') {
      item.inputValue = ''
    }
  })
}

const Launchform = (row: any) => {
  addUsersParms.value.chiName = row[3].inputValue
  addUsersParms.value.deptNo = row[4].selectValue.split(' ')[0]
  addUsersParms.value.engName = row[2].inputValue
  addUsersParms.value.posId = row[5].selectValue.split(' ')[0]
  addUsersParms.value.remark = row[6].inputValue
}

// 派工部门查询
const DispatchDepartmentMethods = async () => {
  try {
    const result = await DispatchDepartment()
    // formList2.value[8].selectOptions = EvaluatesTheArrayReturnValue(result)
    DispatchDepartmentList.value = EvaluatesTheArrayReturnValue1(result)
  } catch (error) {
    JMessage.error('职位查询出错')
  }
}

const DispatchDepartmentList = ref([])

// 添加用户
const postQueryMethods = async () => {
  try {
    let NewArray = []
    const result = await postQuery()
    NewArray = result.reduce((arr: any, item: any) => {
      if (item.posId && item.posName) {
        // 只添加非空的 typeName 和 typeNo
        arr.push(item.posId + ' ' + item.posName)
      }
      return arr
    }, [])
    formList2.value[5].selectOptions = EvaluatesTheArrayReturnValue(NewArray)
    postQueryList.value = EvaluatesTheArrayReturnValue1(NewArray)
  } catch (error) {
    JMessage.error('职位查询出错')
  }
}

const postQueryList = ref([])

const dialogVisible1 = ref(false)

const findData1 = (row: string) => {
  if (row === '保存') {
    addUsersMethods()
  }
  if (row === '删除用户') {
  }
}

const EvaluatesTheArrayReturnValue1 = (ArrayList: any) => {
  return ArrayList.map((item: any, index: any) => {
    return {
      value: item,
      label: item
    }
  })
}

const handleCloseMateriaLKlc5 = () => {
  if (deleteUserMethodsParms.value.userId === '') {
    JMessage.warning('请选择需要删除的数据')
  } else {
    ElMessageBox.confirm('确认要删除数据吗?')
      .then(async () => {
        deleteUserMethods()
      })
      .catch(() => {})
  }
}

// 部门
const DepartmentAllInquiryMethods = async () => {
  let NewArray = []
  const result = await DepartmentAllInquiry()
  NewArray = result.reduce((arr: any, item: any) => {
    if (item.deptNo && item.deptName) {
      // 只添加非空的 typeName 和 typeNo
      arr.push(item.deptNo + ' ' + item.deptName)
    }
    return arr
  }, [])
  formList2.value[4].selectOptions = EvaluatesTheArrayReturnValue(NewArray)
  DepartmentAllInquiryList.value = EvaluatesTheArrayReturnValue1(NewArray)
}

const DepartmentAllInquiryList = ref([])

const EvaluatesTheArrayReturnValue = (ArrayList: any) => {
  return ArrayList.map((item: any, index: any) => {
    return {
      optionKey: index,
      optionValue: item,
      optionLabel: item
    }
  })
}

const formList2 = ref([
  {
    type: 'input',
    inputPlaceholder: '公司',
    inputValue: 'BF'
  },
  {
    type: 'input',
    inputPlaceholder: '用户代码',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '英文名',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '中文名',
    inputValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '部门',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '职务',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '备注',
    inputValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '保存'
  }
])

const findData = (row: string) => {
  if (row === '添加用户') {
    dialogVisible1.value = true
  }
  if (row === '删除用户') {
    handleCloseMateriaLKlc5()
  }
}

// 按钮
const Launchform3 = (row: any) => {
  usersQueryParms.value.chiName = row[1].inputValue
  usersQueryParms.value.posName = row[2].inputValue
  usersQueryParms.value.deptName = row[3].inputValue
  usersQueryMethods()
}

const clickNumber = (row: string) => {
  switch (row) {
    case '1': {
      usersQueryParms.value.lockStatus = null
      break
    }
    case '2': {
      usersQueryParms.value.lockStatus = 'N'
      break
    }
    case '3': {
      usersQueryParms.value.lockStatus = 'Y'
      break
    }
  }
  usersQueryMethods()
}

const formList1 = ref([
  {
    type: 'button',
    checkboxLabel: '添加用户'
  },
  {
    type: 'input',
    inputPlaceholder: '中文名称',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '职务名称',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '部门名称',
    inputValue: ''
  },
  {
    type: 'radio',
    checkboxLabel: '锁定',
    label: '3'
  },
  {
    type: 'radio',
    checkboxLabel: '正常',
    label: '2'
  },
  {
    type: 'radio',
    checkboxLabel: '全部',
    label: '1'
  }
])

// 查询
const isLoading7 = ref(true)

const usersQueryParms = ref<any>({
  chiName: '',
  deptName: '',
  lockStatus: '',
  pageNum: 1,
  pageSize: 40,
  posName: ''
})

const usersQueryTableDate = ref([])

const usersQueryMethods = async () => {
  isLoading7.value = true
  try {
    const result = await usersQuery(usersQueryParms.value)
    usersQueryTableDate.value = result.list.map((item: any) => {
      item.deptName = {
        selectValue: item.deptName || '',
        options: DepartmentAllInquiryList.value
      }

      item.posName = {
        selectValue: item.posName || '',
        options: postQueryList.value
      }

      if (item.lockStatus === 'N') {
        item.lockStatus = {
          selectValue: '正常使用' || '',
          options: [
            { value: '正常使用', label: '正常使用', item: '1' },
            { value: '禁止使用', label: '禁止使用', item: '2' }
          ]
        }
      } else if (item.lockStatus === 'Y') {
        item.lockStatus = {
          selectValue: '静止使用' || '',
          options: [
            { value: '正常使用', label: '正常使用', item: '1' },
            { value: '禁止使用', label: '禁止使用', item: '2' }
          ]
        }
      } else {
        item.lockStatus = {
          selectValue: item.lockStatus || '',
          options: [
            { value: '正常使用', label: '正常使用', item: '1' },
            { value: '禁止使用', label: '禁止使用', item: '2' }
          ]
        }
      }

      item.drawDept = {
        selectValue: item.drawDept || '',
        options: DepartmentAllInquiryList.value
      }

      item.dispatchDept = {
        selectValue: item.dispatchDept || '',
        options: DispatchDepartmentList.value
      }

      if (item.netFlag === 'Y') {
        item.netFlag = {
          selectValue: '外网' || '',
          options: [
            { value: '内网', label: '内网', item: '1' },
            { value: '外网', label: '外网', item: '2' }
          ]
        }
      } else if (item.netFlag === 'N') {
        item.netFlag = {
          selectValue: '内网' || '',
          options: [
            { value: '内网', label: '内网', item: '1' },
            { value: '外网', label: '外网', item: '2' }
          ]
        }
      } else {
        item.netFlag = {
          selectValue: item.netFlag || '',
          options: [
            { value: '内网', label: '内网', item: '1' },
            { value: '外网', label: '外网', item: '2' }
          ]
        }
      }

      return item
    })
    total.value = result.total
    isLoading7.value = false
  } catch (error) {
    isLoading7.value = false
    JMessage.error('查询出错')
  }
}

const total = ref(0)

const handleSizeChangeTk = (val: number) => {
  usersQueryParms.value.pageSize = val
  usersQueryMethods()
}

const handleCurrentChangeTk = (val: number) => {
  usersQueryParms.value.pageNum = val
  usersQueryMethods()
}

onMounted(() => {
  usersQueryMethods()
  DepartmentAllInquiryMethods()
  postQueryMethods()
  DispatchDepartmentMethods()
})

// 表格数据
const tableHeader = ref([
  {
    label: '公司',
    prop: 'abbrName',
    change1: true,
    type: 'input'
  },
  {
    label: '用户代码',
    prop: 'userId',
    type: 'input'
  },
  {
    label: '英文名',
    prop: 'engName',
    type: 'input'
  },
  {
    label: '中文名',
    prop: 'chiName',
    type: 'input'
  },
  {
    label: '部门',
    prop: 'deptName',
    type: 'select'
  },
  {
    label: '职务',
    prop: 'posName',
    type: 'select'
  },
  {
    label: '最后登录时间',
    prop: 'lastLogin',
    type: 'input',
    change1: true
  },
  {
    label: '锁定状态',
    prop: 'lockStatus',
    type: 'select'
  },
  {
    label: '领用部门',
    prop: 'drawDept',
    type: 'select'
  },
  {
    label: '派工部门',
    prop: 'dispatchDept',
    type: 'select'
  },
  {
    label: '外网标记',
    prop: 'netFlag',
    type: 'select'
  },
  {
    label: '备注',
    prop: 'remark',
    type: 'input'
  }
])
</script>

<style lang="less" scoped>
h1 {
  font-size: 16px;
}
</style>
